<template>
  <!--  面包屑导航-->
  <el-breadcrumb separator=">">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>商品分类</el-breadcrumb-item>
  </el-breadcrumb>
  <!--  卡片区域-->
  <el-card>
    <!--添加分类区域-->
    <el-row>
      <el-col :span="5">
        <el-button type="primary" @click="openCateDialog">添加分类</el-button>
      </el-col>
    </el-row>
    <!--    表格区域-->
    <el-table :data="categories" border stripe>
      <el-table-column type="expand">
        <template v-slot="scope">
          <!--          渲染第一级-->
          <el-row class="vcenter">
            <el-col :span="5">
              <el-tag closable effect="dark" type="success" @close="removeCategories(scope.row, scope.row.cat_id)">{{scope.row.cat_name}}</el-tag>
              <i class="iconfont icon-youjiantou"></i>
            </el-col>
            <!--            渲染第二级-->
            <el-col :span="19">
              <el-row class="vcenter" v-for="(item2, i2) in scope.row.children" :key="item2.cat_id">
                <el-col :span="5">
                  <el-tag closable effect="dark" type="warning" @close="removeCategories(scope.row, item2.cat_id)">{{item2.cat_name}}</el-tag>
                  <i class="iconfont icon-youjiantou"></i>
                </el-col>
                <!--                渲染第三级-->
                <el-col :span="19">
                  <el-tag closable effect="dark" v-for="(item3, i3) in item2.children" :key="item3.cat_id" @close="removeCategories(scope.row, item3.cat_id)">
                    {{item3.cat_name}}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index"/>
      <el-table-column prop="cat_name" label="分类名称"/>
      <el-table-column prop="cat_deleted" label="是否删除">
        <template v-slot="scope">
          <i class="iconfont icon-dagou" v-if="scope.row.cat_deleted"></i>
          <i class="iconfont icon-dacha" v-else style="color: red"></i>
        </template>
      </el-table-column>
      <el-table-column prop="cat_level" label="分类级别">
        <template v-slot="scope">
          <el-tag type="danger" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button type="primary" @click="openEditCateDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="warning" @click="deleteEditCateMessageBox(scope.row.cat_id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页区域-->
    <el-pagination
        v-model:currentPage="queryCategoriesInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryCategoriesInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="cateTotal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!--    添加分类对话框-->
    <el-dialog v-model="cateDialogVisible" title="添加分类" @close="closeCateDialog">
      <el-form ref="cateFormRef" :model="cateForm" :rules="cateRules">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="cateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
              v-model="casCarderValue"
              :options="casCarderOptions"
              :props="casCarderProps"
              @expand-change="casCarderHandleChange"
              clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCasCarder">确认</el-button>
      </span>
      </template>
    </el-dialog>
    <!--    编辑商品分类-->
    <el-dialog v-model="editCateDialogVisible" title="修改商品分类">
      <el-form ref="editCateRef" :model="editCateForm" :rules="editCateRules" @close="closeEditCategoriesDialog">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEditCateDialog">确认</el-button>
      </span>
      </template>
    </el-dialog>
  </el-card>

</template>

<script lang="ts" setup>
import {DeleteRole, GetCategoriesList, DeleteCategories, AddCategories,GetCategoriesById, UpdateCategories} from "@/api";
import {reactive, ref} from 'vue'
import {ICategoriesInfo, IAddCateParams, IUpdateCateInfo} from "@/util/interface";
import {ElForm, ElMessage, ElMessageBox} from "element-plus";
import {MessageBox} from "@element-plus/icons-vue";

const categories = ref([])
const cateTotal = ref(0)
const queryCategoriesInfo: ICategoriesInfo = {
  type: 3,
  pagenum: 1,
  pagesize: 5,
}
const getCategories = async ()=>{
  const {data: res} = await GetCategoriesList(queryCategoriesInfo)
  // console.log(res)
  if(res.meta.status !== 200){return ElMessage.error('获取商品分类数据失败')}
  categories.value = res.data.result
  cateTotal.value = res.data.total
}
getCategories()
//删除标签
const removeCategories = (cate: any, id: number) =>{
  ElMessageBox.confirm(
      '将永久删除角色信息，是否继续？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const {data: res} = await DeleteCategories(id)
        console.log(res)
        if (res.meta.status !== 200) {
          return ElMessage.error('删除失败')
        }
        //重新获取角色列表
        getCategories()
        ElMessage.success('已成功删除')
      })
      .catch(() => {
        ElMessage.info('已取消删除')
      })
}
//分页器,size-change
const handleSizeChange = (newSize: number) =>{
  // console.log(newSize)
  queryCategoriesInfo.pagesize = newSize
  getCategories()
}
//分页器,current-change
const handleCurrentChange = (newCurrentPage: number) =>{
  // console.log(newCurrentPage)
  queryCategoriesInfo.pagenum = newCurrentPage
  getCategories()
}
//添加分类对话框
const cateDialogVisible = ref(false)
const openCateDialog = ()=>{
  cateDialogVisible.value = true
}
// const cateFormRef: any = ref(null)
const cateFormRef = ref<InstanceType<typeof ElForm>|null>(null)
const cateForm : IAddCateParams = reactive({cat_pid: 0, cat_name: '', cat_level: 0})
const cateRules = ref({
  cat_name: [{required: true, message: '请输入分类名称', trigger: 'blur'},]
})

//级联选择器数据源
const casCarderOptions = ref([])
//级联选择器配置选项
const casCarderProps = reactive({
  expandTrigger: 'hover',
  value: 'cat_id',
  label: 'cat_name',
  children: 'children',
  checkStrictly: true,
})
//级联选择器选中项绑定值
const casCarderValue = ref()
//获取所有的一级二级分类数据
const getOneTwoCategories = async ()=>{
  const {data: res} = await GetCategoriesList({type: 2})
  // console.log(res)
  if(res.meta.status !== 200) {return ElMessage.error(res.meta.msg)}
  casCarderOptions.value = res.data
  ElMessage.success(res.meta.msg)
}
getOneTwoCategories()

//级联选择器change事件
const casCarderHandleChange =(changeVal: any)=>{
  console.log(changeVal)
  console.log(changeVal.length)
  if (changeVal.length > 0){
    cateForm.cat_pid = changeVal[changeVal.length-1]
    cateForm.cat_level = changeVal.length
  }
  else{
    cateForm.cat_pid = 0
    cateForm.cat_level = 0
  }
}
//级联选择器确认
const confirmCasCarder = () =>{
  cateFormRef.value?.validate(async (valid?: boolean)=>{
    if (!valid){ return ElMessage.error('添加分类失败')}
    const {data: res} = await AddCategories(cateForm)
    console.log(res)
    if (res.meta.status !== 201) {return ElMessage.error('添加分类失败,'+res.meta.msg)}
    ElMessage.success('添加分类成功')
    cateDialogVisible.value = false
    getCategories()
  })

}
//关闭添加分类对话框
const closeCateDialog = ()=>{
  cateFormRef.value?.resetFields()
  cateForm.cat_pid = 0
  cateForm.cat_level = 0

}
//编辑商品分类
const editCateDialogVisible = ref(false)
const editCateRef: any = ref(null)
const editCateForm: IUpdateCateInfo = reactive({
  cat_id: 0,
  cat_name: '',
})
const editCateRules = reactive({
  cat_name: [{required:true, message:'请输入分类名称', trigger: 'blur'}]
})
//重置表单信息
const closeEditCategoriesDialog = ()=>{
  editCateRef.value.resetFields()
}
//打开编辑商品分类对话框
const openEditCateDialog = async (id: number)=>{
  const {data: res} = await GetCategoriesById(id)
  if(res.meta.status !== 200) {return ElMessage.error('获取分类信息出错')}
  editCateForm.cat_name = res.data.cat_name
  editCateForm.cat_id = res.data.cat_id
  editCateDialogVisible.value = true
}
//确认修改商品分类信息
const confirmEditCateDialog = async ()=>{
  const {data: res} = await UpdateCategories(editCateForm)
  console.log(res)
  getCategories()
  editCateDialogVisible.value = false
}
// 删除商品分类信息
const deleteEditCateMessageBox = (id: number)=>{
  ElMessageBox.confirm(
      '将永久删除商品分类信息，是否继续?',
      '删除商品分类信息',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const {data: res} = await DeleteCategories(id)
        console.log(res)
        if (res.meta.status !== 200) {return ElMessage.error('删除失败')}
        getCategories()
        ElMessage.success('删除成功')
      })
      .catch(() => {
        ElMessage.error('删除失败')
      })
}
</script>

<style lang="less" scoped>
.vcenter{
  display: flex;
  align-items: center;
}
.el-tag{
  margin-bottom: 10px;
}
.el-cascader{
  width: 100%;
}
</style>